package org.xxpay.pay.channel.huypay;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xxpay.core.common.domain.api.AbstractRes;
import org.xxpay.core.common.domain.api.ApiBuilder;
import org.xxpay.core.common.domain.api.PayRes;
import org.xxpay.core.common.domain.api.msg.QueryRetMsg;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.common.util.JsonUtil;
import org.xxpay.core.common.util.MyBase64;
import org.xxpay.core.common.util.MyLog;
import org.xxpay.core.common.vo.DBApplicationConfig;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;
import org.xxpay.pay.mq.BaseNotify4MchPay;

import java.util.Map;
import java.util.TreeMap;

@Service
public class HuypayPaymentService extends BasePayment {

    @Autowired
    public BaseNotify4MchPay baseNotify4MchPay;

    private static final MyLog _log = MyLog.getLog(HuypayPaymentService.class);

    @Override
    public String getChannelName() {
        return HuypayConfig.CHANNEL_NAME;
    }

    /**
     * 支付
     * @param payOrder
     * @return
     */
    @Override
    public AbstractRes pay(PayOrder payOrder) {
        String channelId = payOrder.getChannelId();
        AbstractRes retObj;
        switch (channelId) {
            case HuypayConfig.CHANNEL_NAME_ALIPAY_QR :
                retObj = doPay(payOrder, HuypayConfig.CHANNEL_PAY_TYPE);
                break;
            default:
                retObj = ApiBuilder.bizError("不支持的渠道[channelId="+channelId+"]");
                break;
        }
        return retObj;
    }

    /**
     *
     * @param payOrder
     * @return
     */
    public AbstractRes doPay(PayOrder payOrder, String type) {
        HuypayConfig huypayConfig = new HuypayConfig(getPayParam(payOrder));
        PayRes retObj = ApiBuilder.buildSuccess(PayRes.class);
        DBApplicationConfig dbConfig = getDBApplicationConfig();
        Map<String, Object> post= new TreeMap<>();
        post.put("merid", huypayConfig.getMerId()); // 商户ID
        post.put("mchorderno", payOrder.getPayOrderId());// 订单号
        post.put("serverurl", super.getNotifyUrl(getChannelName(), dbConfig));// 回调地址
        post.put("paytype", HuypayConfig.CHANNEL_PAY_TYPE);// 支付方式
        post.put("tranamt", AmountUtil.convertCent2Dollar(payOrder.getAmount()+""));// 交易金额
        post.put("shopid", huypayConfig.getShopId());// 门店编码

        try {
            //生成签名
            Map<String, Object> post1 = new TreeMap<>();
            post1.put("app_key", huypayConfig.getAppKey()); // 应用账号
            post1.put("method", "trade.pay"); // 接口名称
            post1.put("timestamp", System.currentTimeMillis()/1000); // 时间戳
            post1.put("version", "1.0.1"); // 商户ID

            Map<String, Object> post2 = new TreeMap<>();
            post2.putAll(post);
            post2.putAll(post1);
            JSONObject json = new JSONObject(post);
            post1.put("biz_content", json.toJSONString()); //合并真正提交的参数JSON
            post1.put("sign", HuypayUtils.getSign(post1, huypayConfig.getAppSecret()));//商户密钥,请自行修改
            _log.info("{}请求数据:{}", getChannelName(), post1);
            String params = HuypayUtils.genUrlParams(post1);
            String result = HuypayUtils.sendPostJson(huypayConfig.getReqUrl(), params);
            _log.info("{}返回数据:{}", getChannelName(), result);
            JSONObject jsonObject = JsonUtil.getJSONObjectFromJson(result);
            String code = jsonObject.getString("code");
            if("0".equals(code)) {
                JSONObject data = jsonObject.getJSONObject("body");
                String payUrl = data.getString("payinfo");     // 支付URL
                int updateCount = commonService.payOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
                _log.info("[{}]更新订单状态为支付中:payOrderId={},payUrl={},payType={},result={}", getChannelName(), payOrder.getPayOrderId(), payUrl, type, updateCount);
//                retObj.setJumpInfo("<script>location.href='" + payUrl + "';</script>", payUrl);
                String toPayUrl = dbConfig.getConfig4PayUrl() + "/"+ HuypayConfig.CHANNEL_NAME+"/pay_" + type + ".htm";
//                String codeImgUrl = dbConfig.getConfig4PayUrl() + "/qrcode_img_get?url=" + payUrl + "&width=200&height=200";
//                retObj.setCodeImgUrl(codeImgUrl);

                JSONObject paramObj = new JSONObject();
                paramObj.put("qrUrl", payUrl);
                paramObj.put("payOrderId", payOrder.getPayOrderId());
                paramObj.put("payAmount", payOrder.getPaymentAmount());
                paramObj.put("channelId", payOrder.getChannelId());
                String param = MyBase64.encode(paramObj.toJSONString().getBytes());
                toPayUrl += "?param=" + param;
                StringBuffer payForm = new StringBuffer();
                payForm.append("<form style=\"display: none\" action=\""+toPayUrl+"\" method=\"post\">");
                payForm.append("<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >");
                payForm.append("</form>");
                payForm.append("<script>document.forms[0].submit();</script>");
                retObj.setJumpInfo(payForm.toString(), toPayUrl);
                return retObj;
            }else {
                String msg = jsonObject.getString("message");
                return ApiBuilder.bizError("调起通道失败[通道提示：" + msg +"]");
            }
        } catch (Exception e) {
            _log.error(e, "");
            return ApiBuilder.bizError("调起通道异常");
        }
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public QueryRetMsg query(PayOrder payOrder) {
        String logPrefix = "【" + getChannelName() + "支付订单查询】";
        String payOrderId = payOrder.getPayOrderId();
        HuypayConfig huypayConfig = new HuypayConfig(getPayParam(payOrder));
        _log.info("{}开始查询,payOrderId={}", logPrefix, payOrderId);
        return QueryRetMsg.waiting();
    }

}
